const path = require("path");
// md -> json
const mdToJson = require("../utils/mtj");
const { deepJson, resolveAttr } = require("../utils/deepJson");
// config
const { style, outpath, modpath } = require("../../config.json");
// json -> html
const { stringify } = require("himalaya");
const { compileEJS, writeEJS } = require("../utils/compile");
const { getFileNames } = require("../utils/generator");

async function writeBody(userpath, sourcename, outname) {
	const jsonx = mdToJson(path.join(userpath, sourcename));
	const names = getFileNames(modpath);
	// 处理 md 的 json 形式
	deepJson(jsonx, (node) => {
		for (let filename of names) {
			if (node.tagName === filename) {
				resolveAttr(node, "class", style[filename].classname);
				break;
			}
		}
	});
	const mdHtml = stringify(jsonx);
	// 填入模板
	const data = await compileEJS("temp/base.html.ejs", { data: mdHtml });
	// 写入文件
	return writeEJS(outpath, outname, data, false);
}

module.exports = writeBody;
